#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import tempfile
import yaml

from oriolustrotter.core import DownloadError, Indexer
from oriolustrotter.fetchers.wgetfetcher import WgetFetcher
from oriolustrotter.fetchers.persistentfetcher import PersistentFetcher
from orioluspith.packets.configreader import ConfigReader

class Trotter:
    def __init__(self, indexer):
        self.__indexer = indexer

    def update(self):
        self.__indexer.update()

    def get_versions(self, packet_name):
        return self.__indexer.get_versions(packet_name)

    def download(self, packet_name, packet_version=""):
        try:
            if packet_version in [None, (), []]:
                return self.__indexer.download(packet_name)
            else:
                return self.__indexer.download(packet_name, packet_version)
        except DownloadError:
            raise

    def get_packet_list(self):
        return self.__indexer.get_packet_list()

    def get_output_path(self):
        return self.__indexer.get_output_path()

class IndexerFactory:
    def get_indexer(self, options):
        cache = os.path.abspath(tempfile.mkdtemp())
        workdir = os.path.expanduser("~/.trotter")
        fetcher = WgetFetcher
        
        if "workdir" in options.keys():
            workdir = options["workdir"]
            
        if "fetcher" in options.keys() and options["fetcher"] == "builtin":
            fetcher = PersistentFetcher

        if "timeout" in options.keys() and type(options["timeout"]) == int:
            timeout = options["timeout"]
        else:
            timeout = 30
        
        if "verification" in options.keys() and options["verification"] == True:
            verification = True
        else:
            verification = False
        
        if "keyring" in options.keys():
            return Indexer(cache, workdir, fetcher, timeout, verification, options["keyring"])
        else:
            return Indexer(cache, workdir, fetcher, timeout, verification)
        
class TrotterFactory:
    class __impl:
        def get_trotter(self, options):
            indexer = IndexerFactory().get_indexer(options)

            return Trotter(indexer)

    __instance = None
    
    def __init__(self):
        if TrotterFactory.__instance is None:
            TrotterFactory.__instance = TrotterFactory.__impl()

        self.__dict__['_TrotterFactory__instance'] = TrotterFactory.__instance

    def __getattr__(self, attr):
        return getattr(self.__instance, attr)

    def __setattr__(self, attr, value):
        return setattr(self.__instance, attr, value)